package dissertation.extensions.generate.entitymanager.control;

import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.generation.OverrideImplementUtil;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiFile;
import dissertation.common.utils.WriteAction;
import dissertation.services.ejbclass.EJBClassService;
import dissertation.services.ejbfield.EJBFieldService;
import dissertation.services.ejbclass.IEJBClassService;
import dissertation.services.ejbfield.IEJBFieldService;
import org.jetbrains.annotations.NotNull;

import static dissertation.common.constants.Constants.*;

public class EntityManagerCodeInsightActionHandler implements CodeInsightActionHandler {
    private IEJBClassService ejbClassService;
    private IEJBFieldService ejbFieldService;

    public EntityManagerCodeInsightActionHandler() {
        ejbClassService = new EJBClassService();
        ejbFieldService = new EJBFieldService();
    }

    @Override
    public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile psiFile) {
        final PsiClass aClass = OverrideImplementUtil.getContextClass(project, editor, psiFile, false);
        if (aClass != null) {
            final PsiField psiField = ejbFieldService.createFieldFromText(project, "private EntityManager entityManager;");
            ejbFieldService.annotateEJBField(psiField, PERSISTENCE_CONTEXT_ANNOTATION_NAME);

            Runnable cmd = new Runnable() {
                @Override
                public void run() {
                    ejbClassService.addImportStatement(aClass, PERSISTENCE_PACKAGE);
                    aClass.add(psiField);
                }
            };
            CommandProcessor.getInstance().executeCommand(project, new WriteAction(cmd), null, null);
        }
    }

    @Override
    public boolean startInWriteAction() {
        return true;
    }
}
